
const fs=require("fs")
const {uploadInfoService,getavatarService,uploadAvatarURl,uploadsPictrue,getFileByFileNameService}=require("../service/FileService")
const {UPLOAD_PATH,APP_HOST,APP_PORT,PICTURE_PATH}=require("../app/config")
class FileController{
    //上传文件
     async uploadInfo(ctx,next){
         const {filename,mimetype,size}=ctx.req.file;
         const {id}=ctx.user
         console.log(ctx.user)
         console.log(ctx.req.file)
         const result=await uploadInfoService(filename,mimetype,size,id)
          //保存数据
         const avatarUrl=`${APP_HOST}:${APP_PORT}/user/${id}/avatar`
         await uploadAvatarURl(avatarUrl,id)
         ctx.body="上传文件成功"
     }
     //查看文件
     async getavatar(ctx,next){
         ///获取信息
         const {userid}=ctx.params
         const result=await getavatarService(userid)
         //设置返回的类型才能展示图片
          ctx.response.set("content-type",result[0].mimetype)
         //展示图片  
         ctx.body=fs.createReadStream(`${UPLOAD_PATH}/${result[0].filename}`)
     }
     //上传多个文件
     async uploadsInfo(ctx,next){
         //获取文件 信息
         const {momentid}=ctx.query;
         console.log(momentid)
         console.log(ctx.req.files)
         for (const file of ctx.req.files) {
             const {filename,mimetype,size}=file
             await uploadsPictrue(filename,mimetype,size,momentid)
         }
         ctx.body="上传成功"
     }
//查看动态图片
    async getFileByFilename(ctx,next){
        //获取参数 
        let {filename}=ctx.params;
        //查询
        const result= await getFileByFileNameService(filename)
        //获取类型
        const {type}=ctx.query;
        console.log(type)
        const types=["small","middle","large"]
     
        //some是数组函数返回的是boolean值
        if(types.some(item => item===type)){
            console.log(typeof(filename))
            console.log(typeof(type))
            filename=filename+"-"+type
            console.log(filename+"-"+type)
            
        }
      
        console.log(result)
        //设置返回类型根据查询信息
        ctx.response.set("content-type",result[0].mimetype)
        ctx.body=fs.createReadStream(`${PICTURE_PATH}/${filename}`)
       
    }

}
module.exports=new FileController()